package com.ruoyi.video.service.impl;

import com.ruoyi.common.domain.video.VideoFile;
import com.ruoyi.common.domain.video.VideoRecord;
import com.ruoyi.video.mapper.VideoFileMapper;
import com.ruoyi.video.mapper.VideoRecordMapper;
import com.ruoyi.video.service.IVideoRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VideoRecordServiceImpl  implements IVideoRecordService {

    @Autowired
    private VideoRecordMapper videoRecordMapper;
    @Autowired
    private VideoFileMapper videoFileMapper;

    @Override
    public List<VideoRecord> selectList(VideoRecord record) {
        return videoRecordMapper.selectList(record);
    }

    @Override
    public int updateVideoRecord(VideoRecord record) {
        if(record.getFile().getId() == null) {
            if(saveFile(record) <= 0) {
                return 0;
            }
            record.setFileId(record.getFile().getId());
        }
        return videoRecordMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int saveVideoRecord(VideoRecord record) {
        if(saveFile(record) <= 0) {
            return 0;
        }
        record.setFileId(record.getFile().getId());
        return videoRecordMapper.insertSelective(record);
    }

    private int saveFile(VideoRecord record) {
        // 保存关联视频信息
        VideoFile file = record.getFile();
        file.setRefNum(1);
        file.setCreateBy(record.getCreateBy());
        file.setCreateTime(record.getCreateTime());
        file.setName(record.getName());
        file.setRemark(record.getRemark());
        file.setDirId(record.getDirId());
        return videoFileMapper.insertSelective(file);
    }

    @Override
    public int delete(VideoRecord record) {
        VideoFile file = videoFileMapper.selectByPrimaryKey(record.getFileId());
        if(file != null) {
            videoFileMapper.updateByPrimaryKeySelective(new VideoFile(file.getId(), file.getRefNum() - 1));
        }
        return videoRecordMapper.deleteByPrimaryKey(record.getId());
    }

    @Override
    public VideoRecord findById(Long id) {
        VideoRecord record = videoRecordMapper.selectByPrimaryKey(id);
        if(record == null) {
            return null;
        }
        record.setFile(videoFileMapper.selectByPrimaryKey(record.getFileId()));
        return record;
    }

    @Override
    public VideoRecord selectByPrimaryKey(Long id) {
        return videoRecordMapper.selectByPrimaryKey(id);
    }
}
